Skip to content

Fix ImageData pixel size on narrow canvases - #2637

Open
bardrop wants to merge 1 commit into
Automattic:masterfrom
bardrop-oss:fix-imagedata-pixel-size
Open

bardrop wants to merge 1 commit into
Automattic:masterfrom
bardrop-oss:fix-imagedata-pixel-size

Conversation

@bardrop

@bardrop bardrop commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for contributing!

  • Have you updated CHANGELOG.md?

Fixes #2623

createImageData(), getImageData() and putImageData() worked out the bytes per pixel as canvas->stride() / width. Cairo pads every row to 4 bytes, so on a narrow canvas this ratio is not the pixel size. A 1px wide A8 canvas has a 4 byte stride, so:

  • createImageData(1, 2) returned 8 bytes instead of 2 (same for A1 and RGB16_565),
  • getImageData() returned padded rows (a 1x3 A8 read gave 12 bytes),
  • putImageData() read the source rows at the wrong offsets.

The fix adds a small imageDataBytesPerPixel() helper (4 for ARGB32/RGB24/RGB30, 2 for RGB16_565, 1 for A8) and uses it in all three. A1 stays bit-packed in createImageData() (ceil(w * h / 8), which is what the existing A1 test expects). I didn't reuse Canvas::approxBytesPerPixel() because it returns 3 for RGB30, which would change the RGB30 createImageData() size.

It isn't only 1px canvases: createImageData() kept the fraction, so a 21px wide A8 canvas (24 byte stride) gave 14 bytes for createImageData(2, 6) instead of 12. When the width is already aligned, nothing changes.

Testing

  • Three new tests in test/canvas.test.js (create/get/put on 1px wide A8, A1 and RGB16_565 canvases). All three fail on master, pass with the fix. npm test: 310 passing.
  • WPT (npx mocha test/wpt/generated/*.js): same 114 failures before and after, none new.

Built locally on macOS arm64 with zig 0.16.0.

@bardrop
bardrop force-pushed the fix-imagedata-pixel-size branch from 2440858 to f401105 Compare November 14, 2026 00:11
createImageData(), getImageData() and putImageData() took the bytes per
pixel from the Cairo stride divided by the canvas width. The stride pads
each row to 4 bytes, so on a narrow A8, A1 or RGB16_565 canvas the ratio
was too big (a 1px wide A8 canvas has a 4 byte stride): createImageData
returned too much data, getImageData used a padded row step and
putImageData read the source rows at the wrong offsets.

Use the pixel size of the format instead. A1 stays bit-packed in
createImageData.

Fixes Automattic#2623
@bardrop
bardrop force-pushed the fix-imagedata-pixel-size branch from f401105 to 921d2e5 Compare November 14, 2026 00:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ImageData pixel lengths and row offsets use Cairo stride as bytes per pixel

1 participant